package cn.hchaojie.camp.day05.oop;

import org.junit.Test;

public class DemoFormatRMB {
	// 查表法
	private static final char[] NAMES = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
	private static String[] BITS = {"", "拾", "百", "仟"};
	
	// 如果当前位数是0，并且前面一位不是0，那就读零
	private static final long[] TEST_DATA = {
		0,
		1000,
		1001,
		1011,
		1010,
		1234,
		1000_5678L,
		1000_0500L,				// 零五百
		1000_0000_1234L,
		1234_5678_1234L,
	};
	
	@Test
	public void testStringBuilder() {
		StringBuilder sb = new StringBuilder();
		
		sb.insert(0, "一十元");
		sb.append("整");		// 往字符串后面加
		sb.insert(0, "三百");	// 这是往前面加字符串

		System.out.println(sb);
	}

	public static void main(String[] args) {
		for (long num : TEST_DATA) {
			System.out.println(format(num));
		}
	}
	
	public static String format(long number) {
		long num4bit = number % 10000;
		long num8bit = number / 10000 % 10000;
		long num12bit = number / 10000_0000;
		
		StringBuilder sb = new StringBuilder();
		if (num4bit > 0) {		// 0到9999元
			String result = format4Bit(num4bit) + "元";
			sb.append(result);
		}
		if (num8bit > 0) {		// 10000 到 9999_9999
			String result = format4Bit(num8bit) + "万";
			sb.insert(0, result);
		}

		if (num12bit > 0) {		// 亿元以上
			String result = format4Bit(num12bit) + "亿";
			sb.insert(0, result);
		}

		return sb.toString();
	}

	// 1234				= 元
	// 1234 5678		= 万
	// 1234 5678 1234	= 亿
	public static String format4Bit(long number) {
		if (number <= 0 || number >= 10000) return "";
		
		// String str = "";	// 字符串连接 用 StringBuilder, StringBuffer
		StringBuilder sb = new StringBuilder();
		
		int bit = 0;
		boolean isLastZero = true;	// 记录前面一位是否为0
		while (number > 0) {
			int num = (int) (number % 10);
			
			if (num != 0) {
				sb.insert(0, BITS[bit]);
				sb.insert(0, NAMES[num]);
			} else {
				// num == 0
				// 如果当前位数是0，并且前面一位不是0，那就读零
				if (isLastZero == false) {
					sb.insert(0, NAMES[0]);
				}
			}
			
			isLastZero = (num == 0);
			
			number /= 10;
			bit++;
		}

		return sb.toString();
	}
}
